/**
 * Time:2022/1/4 10:07
 * Author:
 * Description:
 */

#include "KMmap.h"


KMmap::KMmap(const char *_filePointer, int _mmapBlockSize) {
    filePointer = _filePointer;
    mmapBlockSize = _mmapBlockSize;
    __android_log_print(ANDROID_LOG_INFO, "kmmap", "_mmapBlockSize:%d\n", mmapBlockSize);
}

bool KMmap::initWrite() {
    if (filePointer == NULL || mmapBlockSize <= 0) {
        return false;
    }
    if ((fileFd = open(filePointer, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
        return false;
    }
    /**
          * ftruncate()会将参数fd 指定的文件大小改为参数length 指定的大小。
          * 参数fd 为已打开的文件描述词，而且必须是以写入模式打开的文件。
          * 如果原来的文件大小比参数length 大，则超过的部分会被删去。
          */
    if (0 != ftruncate(fileFd, mmapBlockSize)) {
        return false;
    }
    if ((mmapPointer = (char *) mmap(NULL, mmapBlockSize, PROT_WRITE | PROT_READ, MAP_SHARED, fileFd, 0)) == NULL) {
        return false;
    }
    return true;
}

int KMmap::write(const char *_dataPointer, int _writeLength) {
    if (filePointer == NULL || mmapPointer == NULL) {
        return WRITE_ERROR;
    }
    if (wroteSize + _writeLength >= mmapBlockSize) {
        munmap(mmapPointer, mmapBlockSize);
        mmapPointer = NULL;
        return WRITE_FULL;
    }
    memcpy(mmapPointer + wroteSize, _dataPointer, _writeLength);
    wroteSize += _writeLength;
    return WRITE_SUCCESS;
}

KMmap::~KMmap() {
    (mmapPointer != NULL) ? munmap(mmapPointer, mmapBlockSize) : 0;
    if (fileFd > 0) {
        ftruncate(fileFd, mmapBlockSize);
        close(fileFd);
    }
}